<template>
    <div>
        <div>
            <rui-page :defines="defines">
                <Row class="operation">
                    <Button @click="add" type="primary" icon="md-add">添加规则</Button>
                    <Button @click="init" icon="md-refresh">加载数据</Button>
                </Row>
                <rui-table :defineId="'priorityInfo'"
                           @loadDatas="queryValue"
                           :slots="[{key:'action',slot:'action'}]"
                           ref="priorityInfoTable" :select="false" style="margin-top: -5px">
                    <template slot="action" slot-scope="{ row }">
                        <div>
                            <Button @click="configure(row)" size="small" type="error" style="margin-right: 5px">规则配置</Button>
                            <Button @click="edit(row)" size="small" type="primary" style="margin-right: 5px">编辑</Button>
                            <Button v-if="row.ruleId!==undefined&&row.ruleState==='1'" style="margin-right:5px" type="warning" size="small"
                                    @click="invalid(row)">生效
                            </Button>
                            <Button v-if="row.ruleState==='2'" style="margin-right:5px" type="success" size="small"
                                    @click="invalid(row)">失效
                            </Button>
                        </div>
                    </template>
                </rui-table>
            </rui-page>
        </div>
        <Modal :title="modalTitle" v-model="priorityModalVisible" :mask-closable='false' :width="400">
            <Form ref="priorityForm" :model="priorityForm" :label-width="80" :rules="priorityFormValidate">
                <FormItem label="规则类型" prop="ruleType" style="margin-top: 20px">
                    <Select v-model="priorityForm.ruleType" v-bind:disabled="diasabledInput">
                        <Option v-for="item in ruleTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="分单时间" prop="time">
                    <TimePicker v-model="priorityForm.time" format="HH:mm" type="timerange" placement="bottom-end" placeholder="Select time" style="width: 288px"></TimePicker>
                </FormItem>
                <FormItem label="规则名称" prop="regulationName">
                    <Input v-model="priorityForm.regulationName"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelPriority">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="submitPriority">提交</Button>
            </div>
        </Modal>
        <div>
            <Modal v-model="ruleModal" :width="1100" :styles="{top: '90'}" @on-cancel="cancel" :footer-hide="true" style="margin-left: 300px">
                <p slot="header" style="color:#f60;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>分单时间规则配置</span>
                </p>
                <Row>
                    <Card style="margin-top:-15px">
                        <rule-tree v-if="dataLoad" @saved="ruleSaved" :readOnly="ruleReadOnly"
                                   :rule-data="ruleData"
                                   :ruleAtoms="ruleAtoms" :rule-id="ruleId" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario"/>
                    </Card>
                </Row>
            </Modal>
        </div>
    </div>
</template>
<script>
    let priorityInfo = [
        {
            key: 'action',
            title: '操作',
            align: 'center',
            slot: 'action',
            width: 300,
        },
        {
            key: 'regulationName',
            title: '规则名称',
            align: 'center',
        },
        {
            key: 'ruleType',
            title: '规则类型',
            align: 'center',
            render: (h, params) => {
                let enable = '';
                let arr = params.row.ruleType;
                if(arr==="approveSplittingTime"){
                    enable = '信审审核';
                }else{
                    enable = '放款审核';
                }
                return h('div', {
                    domProps: {
                        innerHTML: enable
                    }
                })
            }
        },
        {
            key: 'value',
            title: '输出值',
            align: 'center',
        },
        {
            key: 'ruleState',
            title: '状态',
            align: 'center',
            render: (h, params) => {
                let text = '';
                let color = '';
                let arr = params.row.ruleState;
                let id = params.row.ruleId;
                if(id!==undefined&&arr==="1"){
                    text = '失效';
                    color = '';
                }else if (arr==="2"&&id!=="") {
                    text = '生效';
                    color = 'lightgreen';
                }else if(id===undefined&&arr==="1"){
                    text = '未创建';
                }
                return h('Tag', {
                        props: {
                            type:"dot",
                            color: color
                        }
                    },
                    text,
                )
            }
        },
        {
            key: 'createTime',
            title: '创建时间',
            align: 'center',
            format:'yyyy-MM-dd'
        }
    ];
    import {addSplittingTime,queryRegularValue,updateRuleState} from "@/projects/afs-core-business/api/afs-case/parameter-rules/topRules";
    import ruiRules from '_c/rui-auto/rui-rules/index'
    import {loadRuleDataById} from '_p/basic/api/rule/rule'
    import {queryAtomsByBizType} from '_p/basic/api/rule/ruleAtom'
    export default {
        components: {
            ruleTree:ruiRules
        },
        data(){
            let validate = function(rule, value, callback) {
                if (Array.isArray(value)) { //格式为：daterange、datetimerange检测
                    value.map(function (item) {
                        if (item === "") {
                            return callback("日期不能为空")
                        }
                    })
                } else { //格式为：date、datetime、year、month 检测
                    if (value === '') {
                        return callback("日期不能为空")
                    }
                }
                return callback()
            };
            return{
                show:false,
                modalType: 0,
                modalTitle: "",
                priorityModalVisible:false,
                submitLoading: false,
                priorityForm:{
                    id:"",
                    time:"",
                    ruleType:"",
                    regulationName:"",
                },
                priorityFormValidate: {
                    time: [{required: true, validator: validate,trigger: 'change'}],
                    ruleType: [{required: true, message: "规则类型不能为空", trigger: "change"}],
                    regulationName: [{required: true, message: "规则名称不能为空", trigger: "change"}]
                },
                searchForm:{
                    pageNumber: 1,
                    pageSize: 10,
                    ruleType:"SplittingTime",
                    ruleState:"",
                    id:""
                },
                ruleTypeList:[
                    {
                        value: 'approveSplittingTime',
                        label: '信审审核'
                    },
                ],
                diasabledInput:false,
                //规则变量
                ruleModal:false,
                ruleAtoms:[],
                ruleName:'分单时间',
                ruleGroup:'',
                businessScenario:'',
                ruleData:[],
                dataLoad:false,
                bizType: 'splittingTime',
                ruleId:'',
                param:{
                    id:"",
                    ruleState:"",
                    ruleId:"",
                },
                ruleReadOnly: false
            }
        },
        methods:{
            init(){
                this.queryValue(1,10);
            },
            handleSearch(){
                this.queryValue(1,10);
            },
            handleReset(){
                this.queryValue(1,10);
            },
            queryValue(pageNumber, pageSize){
                this.searchForm.pageNumber = pageNumber;
                this.searchForm.pageSize = pageSize;
                this.searchForm.ruleType = "approveSplittingTime";
                queryRegularValue(this.searchForm).then(res=>{
                    let self = this;
                    res.data.records.forEach(key=>{
                        self.$set(key,"time","");
                    });
                    if(res.code === "0000"){
                        let {records, total} = res.data;
                        this.$refs.priorityInfoTable.updateTableData(records, total);
                    }
                })
            },
            add(){
                this.modalType = 0;
                this.modalTitle = "添加分单时间";
                this.$refs.priorityForm.resetFields();
                this.diasabledInput = false;
                this.priorityModalVisible = true;
            },
            cancelPriority() {
                this.priorityModalVisible = false;
            },
            //提交
            submitPriority() {
                this.$refs.priorityForm.validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            this.submitLoading = true;
                            this.priorityForm.id = "";
                            addSplittingTime(this.priorityForm).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getList();
                                    this.priorityModalVisible = false;
                                }
                            });
                            this.submitLoading = false;
                        }else{
                            this.submitLoading = true;
                            addSplittingTime(this.priorityForm).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getList();
                                    this.priorityModalVisible = false;
                                }
                            });
                            this.submitLoading = false;
                        }
                    }
                });
            },
            ruleSaved(ruleId){
                this.ruleModal = false;
                this.cancel();
                updateRuleState(this.searchForm).then(res=>{
                    if(res.code==="0000"){
                        this.getList();
                    }
                })
            },
            getList() {
                this.searchForm.ruleType = "approveSplittingTime";
                queryRegularValue(this.searchForm).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        let self = this;
                        res.data.records.forEach(key=>{
                            self.$set(key,"time","");
                        });
                        let {records, total} = res.data;
                        this.$refs.priorityInfoTable.updateTableData(records, total);
                    }
                });
            },
            configure(v){
                if(v.ruleState==="2"&&v.ruleId!==undefined){
                    this.ruleReadOnly = true;
                }else{
                    this.ruleReadOnly = false;
                }
                this.ruleModal = true;
                if(v.ruleId!==undefined){
                    this.ruleId = v.ruleId;
                    this.businessScenario = v.id;
                }else {
                    this.ruleId = "";
                    this.businessScenario = v.id;
                }
                this.searchForm.id = v.id;
                this.ruleGroup = v.ruleType;
                this.queryRuleDataById();
                this.queryRuleAtomInfo();
            },
            //失效,失效
            invalid(row){
                this.param.id = row.id;
                this.param.ruleState = row.ruleState;
                this.param.ruleId = row.ruleId;
                updateRuleState(this.param).then(res=>{
                    if(res.code==="0000"){
                        this.$Message.success("操作成功");
                        this.getList();
                    }
                })
            },
            queryRuleDataById(){
                loadRuleDataById((this.ruleId&&this.ruleId!='')?this.ruleId:undefined,"case").then(res=>{
                    if(res.code='0000'){
                        if(res.data.length>0) {
                            this.ruleData.push(...res.data);
                        }
                        this.dataLoad = true;
                    }
                });
            },
            //原子查询
            queryRuleAtomInfo(){
                queryAtomsByBizType(this.bizType,"case").then(res=>{
                    if(res.code=="0000"){
                        this.ruleAtoms = res.data;
                    }
                })
            },
            //弹窗关闭
            cancel () {
                this.ruleId = '';
                this.ruleData = [];
                this.dataLoad = false;
                this.businessScenario = '';
            },
            //编辑
            edit(v){
                this.modalType = 1;
                this.modalTitle = "编辑";
                this.$refs.priorityForm.resetFields();
                for (let attr in v) {
                    if (v[attr] === null) {
                        v[attr] = "";
                    }
                }
                let str = JSON.stringify(v);
                let member = JSON.parse(str);
                this.priorityForm = member;
                let time = [];
                time.push(v.value.slice(0, 5));
                time.push(v.value.slice(6, 11));
                this.priorityForm.time = time;
                let date = v.value.slice(0, 5) + "-" + v.value.slice(6, 11);
                this.diasabledInput = true;
                this.priorityModalVisible = true;
            },
            //搜索
            handleSearch(){
                if(this.searchForm.ruleType === undefined){
                    this.searchForm.ruleType = "SplittingTime";
                }
                queryRegularValue(this.searchForm).then(res=>{
                    if(res.code === "0000"){
                        let self = this;
                        res.data.records.forEach(key=>{
                            self.$set(key,"time","");
                        });
                        let {records, total} = res.data;
                        this.$refs.priorityInfoTable.updateTableData(records, total);
                    }
                })
            }
        },
        computed: {
            defines() {
                return [
                    {
                        id: 'priorityInfo',
                        fields: priorityInfo
                    }
                ]
            }
        },
        //初始化
        mounted() {
            this.init();
        }
    }
</script>
